package com.qf.events.listeners;

import com.qf.entity.SysDevice;
import com.qf.events.DeviceOnOffLineEvent;
import com.qf.service.DeviceService;
import com.qf.utils.RequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * @Author ztf
 * @Date 19:45 2022/1/7
 * 设备状态修改监听
 **/
@Component
public class DeviceStatusChangeListener {
    private DeviceService deviceService;

    @Autowired
    public void setDeviceService(DeviceService deviceService) {
        this.deviceService = deviceService;
    }

    @EventListener
    @Async
    public void onEvent(DeviceOnOffLineEvent event) {
        System.err.println("登录id："+event.getId());
        SysDevice device = new SysDevice();
        device.setCurrentConnectIp(event.getIp());
        device.setDeviceId(event.getId());
        device.setIsOnline(event.getStatus());
        device.setConnectTime(event.getEventTime());
        device.setLostConnectTime(event.getEventTime());
        //如果登陆时有ip地址，则设置登录地域
        if (StringUtils.hasText(event.getIp())){
            device.setConnectLocation(RequestUtil.getLocationByIp(event.getIp()));
        }
        deviceService.updateDeviceOnlineStatus(device);
    }
}
